package com.supercube.system.controller;

import com.supercube.common.annotation.Log;
import com.supercube.common.controller.BaseController;
import com.supercube.common.domain.FileDO;
import com.supercube.common.domain.Tree;
import com.supercube.common.service.FileService;
import com.supercube.common.utils.MD5Utils;
import com.supercube.common.utils.R;
import com.supercube.common.utils.ShiroUtils;
import com.supercube.common.utils.StringUtils;
import com.supercube.sport.yoga.utils.ResultInfo;
import com.supercube.system.domain.MenuDO;
import com.supercube.system.domain.UserDO;
import com.supercube.system.service.MenuService;
import com.supercube.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.web.session.mgt.WebSessionKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Controller
@Api(tags = "Login")
public class LoginController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    MenuService menuService;
    @Autowired
    FileService fileService;
    @Autowired
    UserService userService;
    @GetMapping({"/", ""})
    @ApiOperation(value = "跳转至登录页面", notes = "跳转至登录页面")
    String welcome(Model model) {

        return "redirect:/login";
    }

    @Log("请求访问主页")
    @GetMapping({"/index"})
    @ApiOperation(value = "请求访问主页", notes = "请求访问主页")
    String index(Model model) {
        List<Tree<MenuDO>> menus = menuService.listMenuTree(getUserId());
        model.addAttribute("menus", menus);
        model.addAttribute("name", getUser().getName());
        FileDO fileDO = fileService.get(getUser().getPicId());
        if (fileDO != null && fileDO.getUrl() != null) {
            if (fileService.isExist(fileDO.getUrl())) {
                model.addAttribute("picUrl", fileDO.getUrl());
            } else {
                model.addAttribute("picUrl", "/img/photo_s.jpg");
            }
        } else {
            model.addAttribute("picUrl", "/img/photo_s.jpg");
        }
        model.addAttribute("username", getUser().getUsername());
        return "index_v1";
    }

    @GetMapping("/login")
    String login() {
        return "login";
    }

    @Log("登录")
    @PostMapping("/login")
    @ResponseBody
    @ApiOperation(value = "登录接口", notes = "登录接口")
    R ajaxLogin(String username, String password) {
        password = MD5Utils.encrypt(username, password);
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            // 查询用户信息
            Map map = new HashMap();
            map.put("username",username);
            map.put("password",password);
            List<UserDO> sysUserList = userService.list(map);
            Map data = new HashMap();
            sysUserList.get(0).setPassword(null);
            data.put("user",sysUserList.get(0));
            // 查询用户对应的角色和菜单
            List<String> list  = userService.queryRoleMenu(sysUserList.get(0).getUserId().toString(),"");
            data.put("permissionsList",list);
            Map result = new HashMap();
            result.put("data",data);
            return R.ok(result);
        } catch (AuthenticationException e) {
            return R.error("用户或密码错误");
        }
    }

    /**
     * 验证是否登陆
     */
    @GetMapping("/isAuthenticated")
    @ResponseBody
    @ApiOperation(value = "判断是否登录", notes = "判断是否登录")
    public boolean isAuthenticated(HttpServletRequest request, HttpServletResponse response){
        boolean status = false;
        String  sessionId = "";
        Cookie[] cookies =  request.getCookies();
        for(Cookie cookie : cookies){
            if(Objects.equals(cookie.getName(),"JSESSIONID")){
                sessionId = cookie.getValue();
                break;
            }
        }
        if(StringUtils.isNotBlank(sessionId)){
            try{
                SessionKey key = new WebSessionKey(sessionId,request,response);
                Session se = SecurityUtils.getSecurityManager().getSession(key);
                Object obj = se.getAttribute(DefaultSubjectContext.AUTHENTICATED_SESSION_KEY);
                if(obj != null){
                    status = (Boolean) obj;
                }
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                Session se = null;
                Object obj = null;
            }
        }else{
            logger.info("未获取到sessionId");
        }
        return status;
    }


    @GetMapping("/logout")
    @ApiOperation(value = "退出登录", notes = "退出登录")
    ResultInfo logout() {
        ShiroUtils.logout();
        return ResultInfo.success("退出成功");
    }

    @GetMapping("/main")
    @ApiOperation(value = "主页面", notes = "主页面,登录后默认页面")
    String main() {
        return "main";
    }

}
